package org.carabiner.util;

import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

/**
 * A static utility class for data processing functions.
 * 
 * <p>
 * Carabiner Testing Framework
 * </p>
 * <p>
 * Copyright: <a href="http://www.gnu.org/licenses/gpl.html">GNU Public License</a>
 * </p>
 * 
 * @author Ben Rady (benrady@gmail.com)
 * 
 */
public class DataUtils
{
  private static final String TOKEN_DELIMITER = ":";

  private DataUtils()
  {
  }

  /**
   * Converts an array of bytes into a string of bytes seperated by spaces.
   * 
   * @param byteArray
   *          byte[]
   * @return String
   */
  public static String byteArrayToString(byte[] byteArray)
  {
    StringBuffer buffer = new StringBuffer(byteArray.length);
    for (int i = 0; i < byteArray.length; i++)
    {
      buffer.append(Byte.toString(byteArray[i]));

      // Make sure not to add a space at the end.
      if (i != byteArray.length - 1)
      {
        buffer.append(TOKEN_DELIMITER);
      }
    }
    return buffer.toString();
  }

  /**
   * Converts a string of byte values seperated by spaces into an array of
   * bytes.
   * 
   * @param string
   *          String
   * @return byte[]
   */
  public static byte[] stringToByteArray(String string)
  {
    List byteList = new ArrayList();
    StringTokenizer st = new StringTokenizer(string, TOKEN_DELIMITER);
    while (st.hasMoreTokens())
    {
      byteList.add(new Byte(st.nextToken()));
    }

    byte[] byteArray = new byte[byteList.size()];
    for (int i = 0; i < byteArray.length; i++)
    {
      Byte b = (Byte) byteList.get(i);
      byteArray[i] = b.byteValue();
    }
    return byteArray;
  }
}
